Declare @tmpDate datetime
SET @tmpDate = '1-Jan-2014'

WHILE @tmpDate <= '31-Oct-2014'
BEGIN
	SET @tmpDate = DateAdd(month,1, @tmpDate)
	Select @tmpDate

	DECLARE curUser CURSOR FOR 
	Select distinct UserID from tblUser_Log
	Where Convert(varchar(6), UpdateDate, 112) = Convert(varchar(6), @tmpDate, 112)

	OPEN curUser

	Declare @UserID int, @TeamID int
	FETCH NEXT FROM curUser
	INTO @UserID

	WHILE @@FETCH_STATUS = 0
	BEGIN
		
		Select top 1 @TeamID = TeamID from tblUser_Log
		Where UserID = @UserID
		And Convert(varchar(6), UpdateDate, 112) = Convert(varchar(6), @tmpDate, 112)
		Order By UpdateDate DESC

		Select top 1 * FROM tblUser_Log
		Where UserID = @UserID
		And Convert(varchar(6), UpdateDate, 112) = Convert(varchar(6), @tmpDate, 112)
		Order By UpdateDate DESC

		Update CTI SET CTI.ClosedByTeamID = @TeamID  
		FROM tblCaseTaskIndex CTI
		INNER JOIN tblCaseProfileIndex CPI ON CTI.CaseRefID = CPI.CaseRefID And CTI.CaseSourceID = CPI.CaseSourceID
		Where Convert(varchar(6), CPI.ClosedOn, 112) = Convert(varchar(6), @tmpDate, 112)
		And CPI.ClosedBy = @UserID 

		Update CTI SET CTI.ProcessedByTeamID = @TeamID  
		FROM tblCaseTaskIndex CTI
		INNER JOIN tblCaseProfileIndex CPI ON CTI.CaseRefID = CPI.CaseRefID And CTI.CaseSourceID = CPI.CaseSourceID
		Where Convert(varchar(6), CPI.ClosedOn, 112) = Convert(varchar(6), @tmpDate, 112)
		And CPI.ProcessedBy = @UserID 

		FETCH NEXT FROM curUser
		INTO @UserID
	END

	CLOSE curUser
	DEALLOCATE curUser
END
